<template>
  <el-dialog
    :title="showTitle"
    :visible="showDaglog"
    center
    @close="close"
  >
    <el-form ref="formDom" label-width="120px" :model="formData" :rules="formRules">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" />
      </el-form-item>
      <el-form-item label="标识" prop="description">
        <el-input v-model="formData.description" style="width:80%" />
      </el-form-item>
      <el-form-item prop="code" label="描述">
        <el-input v-model="formData.code" style="width:80%" />
      </el-form-item>
      <el-form-item label="开启">
        <el-switch
          v-model="formData.enVisible"
          inactive-value="0"
          active-value="1"
        />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row>
        <el-button type="primary" @click="btnOk">确定</el-button>
        <el-button @click="close">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addPermission, updatePermission } from '@/api/permission'
export default {
  props: {
    showDaglog: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formData: {
        enVisible: '0', // switch开关
        name: '', // 名称
        description: '', // 标识
        code: '', // 描述
        pid: '',
        type: ''
      },
      // 表单规则
      formRules: {
        name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入描述名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入标识名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    showTitle() {
      return this.id ? '编辑权限' : '新增权限'
    }
  },
  methods: {
    //  添加时渲染 pid 和 type 属性
    updateForm(obj) {
      this.formData.pid = obj.id
      this.formData.type = obj.type + 1
    },
    //  编辑时渲染整个 form表单
    editUpdateForm(obj) {
      this.formData = obj
    },
    //  添加权限
    btnOk() {
      this.$refs.formDom.validate(async(isOk) => {
        if (isOk) {
          //  判断有没有id  如果有id 代表的是 编辑
          if (this.id) {
            await updatePermission({ ...this.formData, id: this.id })
          } else {
            await addPermission(this.formData)
          }
          await this.$parent.getPermission()
          this.$message.success(this.id ? '编辑成功' : '新增成功')
          this.close()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    close() { // 关闭弹出层
      this.$emit('update:showDaglog', false)
      this.$emit('update:id', '')
      this.formData = {
        enVisible: '0', // switch开关
        name: '', // 名称
        description: '', // 标识
        code: '', // 描述
        pid: '', // 标识
        type: ''
      }
    }
  }
}
</script>

<style>

</style>
